import req from "@/utils/req"
import { make } from "@/components/EditorJs/utils/dom"

const uploadApi = (file: any) => req.post(`/cs/upload/free`, file)

export const uploadFn = async (file: File, cb?: (error: any, result?: any) => void, apiFn = uploadApi) => {
	const data = new FormData()
	data.set("file", file)
	try {
		const res: any = await apiFn(data)
		const { url, filename, size } = res
		const obj = {
			url,
			name: file.name,
			size: file.size,
			type: file.type,
		}
		cb && cb(null, obj) // 第一个参数为null表示没有错误
		return obj
	} catch (error) {
		cb && cb(error)
	}
}

export const uploadFreeFileFn = (cb: (error: any, data: any, upLoading?: string) => void) => {
	const fileDom = make("input", "", { type: "file" })
	fileDom.style.display = "none"
	document.body.append(fileDom)
	fileDom.click()
	fileDom.addEventListener("change", async (event: any) => {
		cb(null, null, "start") // 开始上传时调用回调 触发loading
		// 处理文件选择事件
		const file = event.target.files[0]

		try {
			const result = await uploadFn(file, () => document.body.removeChild(fileDom))
			cb(null, result, "end") // 成功时调用回调
		} catch (error) {
			cb(error, null, "end") // 失败时调用回调
		}
	})
}
